﻿/*======================================================================
== Copyright : BlueCurve (c)
== Licence   : Gnu/GPL v2.x
== Author    : Teddy Albina
== Email     : bluecurveteam@gmail.com
== Web site  : http://www.codeplex.com/BlueCurve
========================================================================*/
using System.IO;
using System.Collections;
using System.Collections.PriorityQueue;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;

namespace BlueCurve.Common
{
    public static class Serialization
    {
        /// <summary>
        /// <![CDATA[Serialize a hashtable or a Dictionnary<> to XML]]>
        /// </summary>
        /// <param name="writer">StreamWriter object</param>
        /// <param name="memory">MemoryStrem object</param>
        /// <param name="dictionary">IDictionnary</param>
        /// <returns>string xml</returns>
        public static string Serialize(StreamWriter writer, MemoryStream memory, IDictionary dictionary)
        {
            try
            {
                List<Entry> entries = new List<Entry>(dictionary.Count);
                foreach (object key in dictionary.Keys)
                {
                    entries.Add(new Entry(key, dictionary[key]));
                }
                XmlSerializer serializer = new XmlSerializer(typeof(List<Entry>));
                serializer.Serialize(writer, entries);

                // Read all data in memory
                memory = (MemoryStream)writer.BaseStream;

                // return data
                byte[] temp = memory.ToArray();
                memory.Close();
                memory.Dispose();
                return Encoding.UTF8.GetString(temp, 0, temp.Length);
            }
            catch
            {
                return null;
            }
        }
    }

    public class Entry
    {
        public object Key;
        public object Value;

        public Entry()
        {
        }

        public Entry(object key, object value)
        {
            Key = key;
            Value = value;
        }
    }
}
